<template>
  <div class='container'>
    <div class="btn_wrapper">
      <span class="fontColor">
        说明：目前支持学科和关键字条件筛选
      </span>
      <el-button class="addbtn">
        <i class="el-icon-edit"></i>
        <span @click="$router.push('./new')">新增试题</span>
      </el-button>
    </div>
    <el-form class="formfisrt" ref="form" :model="form" label-width="80px">
      <el-form-item label="学科">
        <el-select placeholder="请选择" @change="getList" v-model="form.subjectID" style="width: 100%;">
            <el-option v-for="item in  SubjectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="二级目录">
        <el-select placeholder="请选择" v-model="form.catalogID" style="width: 100%;">
            <el-option v-for="item in  list" :key="item.id" :label="item.directoryName" :value="item.id"></el-option>
         </el-select>
      </el-form-item>
      <el-form-item label="标签">
        <el-select placeholder="请选择" v-model="form.tags" style="width: 100%;">
          <el-option v-for="item in TagsSimpleList" :key="item.id" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
       <el-form-item label="关键字" prop="keyword">
        <el-input v-model="form.keyword" placeholder="根据题干搜索"></el-input>
      </el-form-item>
       <el-form-item label="试题类型" prop="questionType">
        <el-select v-model="form.questionType" placeholder="根据题干搜索">
          <el-option v-for="(item,index) in questionTypeMap" :key="index" :label="item.label" :value="item.label"></el-option>
        </el-select>
      </el-form-item>
       <el-form-item label="难度" prop="difficulty">
        <el-select v-model="form.difficulty" placeholder="根据题干搜索">
          <el-option v-for="(item,index) in difficultyMap" :key="index" :label="item.label" :value="item.label"></el-option>
        </el-select>
      </el-form-item>
       <el-form-item label="方向" prop="direction">
        <el-select v-model="form.direction" placeholder="根据题干搜索">
          <el-option v-for="(item,index) in directionMap" :key="index" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
     <el-form-item label="录入人">
        <el-select placeholder="请选择" v-model="form.creatorID" style="width: 100%;">
          <el-option label="超级管理员" value="超级管理员"></el-option>
          <el-option label="录入管理员" value="录入管理员"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题目备注" prop="remarks">
        <el-input v-model="form.remarks"></el-input>
      </el-form-item>
      <el-form-item label="企业简称" prop="shortName">
        <el-input v-model="form.shortName"></el-input>
      </el-form-item>
       <el-form-item label="城市">
        <el-select style="width:130px" v-model="form.province" @change="changeProvince" placeholder="请选择">
          <el-option v-for="(item,index) in provinces" :key="index" :label="item" :value="item"></el-option>
        </el-select>
        <el-select style="width:130px" v-model="form.city" placeholder="请选择">
          <el-option v-for="(item,index) in city" :key="index" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="hClose">清除</el-button>
        <el-button type="primary" @click="loadquestionsSearch">搜索</el-button>
      </el-form-item>
    </el-form>
    <div class="el_alert">
      <div class="el_content">
         <i class="el-alert__icon el-icon-info"></i>
         <span class="el_title">数据一共{{total}}条</span>
      </div>
      <i class="el_closebtn el-icon-close" style="display:none"></i>
    </div>
    <div>
      <el-table  :data="tableData" style="width: 100%">
        <el-table-column label="试题编号" prop="number">
        </el-table-column>
        <el-table-column label="学科" prop="subject">
        </el-table-column>
        <el-table-column label="目录" prop="catalog">
        </el-table-column>
        <el-table-column label="题型" prop="questionType">
          <template v-slot="{row}">
              {{questionTypeFn(row.questionType)}}
          </template>
        </el-table-column>
        <el-table-column ref="questionRef" label="题干" prop="question">
          <template v-slot="{row}">
              {{HtmlToText(row.question)}}
          </template>
        </el-table-column>
        <el-table-column label="录入时间">
          <template v-slot="{row}">
            {{fromDate(row.addDate)}}
          </template>
        </el-table-column>
        <el-table-column label="难度">
          <template v-slot="{row}">
            {{formatEmployment(row.difficulty)}}
          </template>
        </el-table-column>
        <el-table-column label="录入人" prop="creator">
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="{row}">
            <el-button @click="hLook(row.id)" size="mini" class="el_button_one el-button--small">
              <i class="el-icon-view"></i>
            </el-button>
            <el-button  @click="$router.push(`/questions/new/?id=${row.id}`)" size="mini" class="el_button_two el-button--small">
              <i class="el-icon-edit" ></i>
            </el-button>
            <el-button @click="hDel(row.id)" size="mini" class="el_button_three el-button--small">
              <i class="el-icon-delete"></i>
            </el-button>
            <el-button @click="hAdd(row.id)" size="mini" class="el_button_four el-button--small">
              <i class="el-icon-check"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="el_pagination">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.page"
        :page-sizes="[2, 6, 20, 30]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      title="题目预览"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="60%">
      <questions-preview v-if="dialogVisible" :id="curId" @close="dialogVisible = false" />
    </el-dialog>
  </div>
</template>

<script>
import QuestionsPreview from '../components/questions-preview.vue'
import dayjs from 'dayjs'
import { list, remove, choiceAdd } from '@/api/hmmm/questions'
import { difficulty, questionType, direction } from '@/api/hmmm/constants'
import { simple as TagsSimpleList } from '../../api/hmmm/tags' // 标签
import { provinces, citys } from '@/api/hmmm/citys'
import { simple } from '../../api/hmmm/subjects'
import { list as directoryList } from '../../api/hmmm/directorys' // 目录
// // 准备枚举对象
const difficultyLaObj = {}
const questionTypeObj = {}
difficulty.forEach(item => {
  difficultyLaObj[item.value] = item.label
})
questionType.forEach(item => {
  questionTypeObj[item.value] = item.label
})

export default {
  components: { QuestionsPreview },
  data () {
    return {
      form: {
        subjectID: '', // 学科
        difficulty: '', // 难度
        questionType: '', // 试题类型
        tags: '', // 标签名称
        province: '', // 企业所在地省份
        city: '', // 企业所在城市
        keyword: '', // 关键字
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        direction: '', // 方向
        creatorID: '', // 录入人
        catalogID: '' // 目录
      },
      q: {
        page: 1,
        pagesize: 2
      },
      total: 0,
      dialogVisible: false,
      curId: '',
      tableData: [],
      directionMap: direction,
      difficultyMap: difficulty,
      questionTypeMap: questionType,
      provinces: [...provinces()],
      city: [],
      list: [],
      SubjectList: [],
      TagsSimpleList: []
    }
  },
  created () {
    this.loadquestions()
    this.getSubject()
    this.TagsList()
  },
  methods: {
    async loadquestions () {
      const res = await list(this.q)
      // console.log(res)
      this.tableData = res.data.items
      this.total = res.data.counts
    },
    async loadquestionsSearch () {
      const res = await list({ ...this.q, ...this.form })
      // console.log(res)
      this.tableData = res.data.items
      this.total = res.data.counts
    },
    // 获取学科列表
    async getSubject () {
      try {
        const { data } = await simple()
        this.SubjectList = data
      } catch (e) {
        console.log(e)
      }
    },
    // 获取二级目录列表
    async getList () {
      console.log(this.form.subjectID)
      try {
        const res = await directoryList({ subjectID: this.form.subjectID })
        // console.log(res)
        this.list = res.data.items
      } catch (e) {
        console.log(e)
      }
    },
    // 获取标签列表
    async TagsList () {
      try {
        const { data } = await TagsSimpleList()
        this.TagsSimpleList = data
      } catch (e) {
        console.log(e)
      }
    },
    // 清除数据
    hClose () {
      this.form = {
        subjectID: '', // 学科
        catalogID: '', // 目录
        tags: '', // 标签
        keyword: '', // 关键字
        questionType: '', // 试题类型
        difficulty: '', // 难度
        direction: '', // 方向
        creatorID: '', // 录入人
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        province: '', // 企业所在地省份
        city: '' // 企业所在城市

      }
      this.list = []
      this.loadquestions()
    },
    formatEmployment (code) {
      return difficultyLaObj[code]
    },
    questionTypeFn (code) {
      return questionTypeObj[code]
    },
    fromDate (data) {
      return dayjs(data).format('YYYY-MM-DD HH:MM:ss')
    },
    HtmlToText (HTML) {
      const content = HTML
      return content
        .replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, '')
        .replace(/<[^>]+?>/g, '')
        .replace(/\s+/g, ' ')
        .replace(/ /g, ' ')
        .replace(/>/g, ' ')
    },
    handleSizeChange (pagesize) {
      this.q.pagesize = pagesize
      this.loadquestions()
    },
    handleCurrentChange (page) {
      this.q.page = page
      this.loadquestions()
    },
    hLook (id) {
      // console.log(id)
      this.curId = id
      this.dialogVisible = true
    },
    changeProvince () {
      this.city = citys(this.form.province)
    },
    // 删除基础题库题
    async hDel (id) {
      try {
        // 提示用户是否删除
        const result = await this.$confirm('确定删除吗？', '提示', { type: 'warning' })
        if (result !== 'confirm') return
        // 发请求
        await remove({ id })
        // console.log(res)
        // 根据结果提醒用户

        this.$message.success('删除成功')
        // 判断：当前是否为最后一条数据，并且当前页>1,需要-1
        if (this.tableData.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        // 重新渲染列表
        this.loadquestions()
      } catch (e) {
        // this.$message.error(e.message)
        console.log(e)
      }
    },
    // 加入精选题库
    async hAdd (id) {
      try {
        // 提示用户是否加入精选
        const result = await this.$confirm('此操作将该题目加入精选, 是否继续?', '提示', { type: 'info' })
        if (result !== 'confirm') return
        // 发请求加入精选 1加入，0移出
        await choiceAdd({ id, choiceState: '1' })
        //  console.log(res)
        // 根据结果提醒用户
        this.$message.success('加入精选成功')
        if (this.tableData.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        this.loadquestions()
      } catch (e) {
        // this.$message.error(e.message)
        console.log(e)
      }
    }

  }
}
</script>

<style scoped lang='scss'>
  .container{
    height: 100%;
    background-color: #fff;
    margin: 10px 10px 0;
    padding: 20px;
  }
  .btn_wrapper .fontColor{
    color: pink;
    font-size: 14px;
  }
  .btn_wrapper .addbtn{
    float: right;
    background-color: #67c23a;
    color: #fff;

  }
  .formfisrt{
    margin-top: 35px;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  .el_alert{
    display: flex;
    justify-content: space-between;
    color: #909399;
    background-color: #f4f4f5;
    width: 100%;
    padding: 8px 16px;
    margin-bottom: 20px;
  }
  .el_content .el_title{
    margin-left: 10px;
  }
  .el_button_one{
    color: #409eff;
    background: #ecf5ff;
    border-color: #b3d8ff;
    border-radius: 50%;
    font-size: 12px;
  }
  .el_button_two{
    color: #67c23a;
    background: #f0f9eb;
    border-color: #c2e7b0;
  }
  .el_button_three{
    color: #f56c6c;
    background: #fef0f0;
    border-color: #fbc4c4;
  }
  .el_button_four{
    color: #e6a23c;
    background: #fdf6ec;
    border-color: #f5dab1;
  }
  .el-button--small{
    padding: 9px;
     font-size: 12px;
     border-radius: 50%;
  }
  .el_pagination{
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }

</style>
